#!/usr/bin/python
# ams@bio.aau.au

from Bio.SeqIO.QualityIO import FastqGeneralIterator
import os.path

def reformat_for_qiime(filehandle, outfilepath):
    """takes a fh of a fastq-illumina file and reformats to fasta for qiime
    the output is compatible with the outpur of the slipt_libraries.py """
    fastqfile = filehandle
    outfile = open(outfilepath, 'w')
    sample = 'AMPA069'
    # TODO should be scripted from a parameters file in future based on 
    # (cellID, lane number and barcode seq)
    
    while True:
        header = fastqfile.readline()
        if not header:
            break
        header = header.strip()
        seqid, barcode_string = header.split()
	read, bad_read, skip, barcode = barcode_string.split(':')
        seq = fastqfile.readline()
        fastqfile.readline()
        fastqfile.readline()
        id = '>{sample} {seqid}:{read} orig_bc={barcode} new_bc= {barcode} bc_diffs=0\n'.format( \
		sample=sample, seqid=seqid[1:], read=read, barcode=barcode)
        if bad_read == 'N':
            outfile.write(id + seq)

    outfile.close()
    
    return fastqfile

